<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ztIot:company:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ztIot:company:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ztIot:company:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="企业名称" align="center" prop="name" />
      <el-table-column label="企业简称" align="center" prop="abbreviation" />
      <el-table-column label="绑定网关" align="center" prop="seriesName" />
      <el-table-column label="自定义域名" align="center" prop="domain" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="电话号码" align="center" prop="contactsPhone" />
      <el-table-column label="企业Logo" align="center" prop="logo" >
        <template slot-scope="scope">
          <el-image :src="downloadUrl+scope.row.logo" style="width:50px;height:50px" v-if="scope.row.logo"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="简介" align="center" prop="intro" /> -->
      <el-table-column label="是否有效" align="center" prop="state" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="toDeviceManager(scope.row)"
            v-hasPermi="['ztIot:company:device']"
          >设备管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="toControlManager(scope.row)"
            v-hasPermi="['ztIot:company:device']"
          >控制管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleAddInterface(scope.row)"
            v-hasPermi="['ztIot:company:edit']"
          >配置接口</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ztIot:company:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ztIot:company:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入企业名称">
            <i18n-input :objId="form.id" type="com.ems.company.domain.SysCompany" property="sysCompany.Name" slot="append"></i18n-input>
          </el-input>
        </el-form-item>
        <el-form-item label="企业简称" prop="abbreviation">
          <el-input v-model="form.abbreviation" placeholder="请输入企业简称" >
            <i18n-input :objId="form.id" type="com.ems.company.domain.SysCompany" property="sysCompany.abbreviation" slot="append"/>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="绑定网关" prop="seriesId">
          <el-select v-model="form.seriesId" placeholder="请选择网关">
            <el-option v-for="item in seriesList" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="自定义域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入自定义域名" />
        </el-form-item>
        <el-form-item label="所属国家" prop="domain">
          <el-select v-model="form.countryId" placeholder="请选择国家">
             <el-option v-for="item in countryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="账号" prop="username" v-if="!form.id">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="电话号码" prop="contactsPhone">
          <el-input v-model="form.contactsPhone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="企业Logo" prop="logo">
          <el-upload v-model="form.logo" style="width: 70%" class="avatar-uploader"
            :headers="{ Authorization: token }" :action="uploadURL" :on-remove="handleRemove"
            :on-success="uploadSuccess" :multiple="false" accept="image/jpg,image/png,image/jpeg" :limit="1"
            :show-file-list="false"
            :file-list="fileList">
            <img v-if="form.logo" :src="downloadUrl+form.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <editor v-model="form.intro" :min-height="192"/>
        </el-form-item>
        <el-form-item label="是否有效" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 接口配置 -->
    <el-dialog title="企业接口配置" :visible.sync="interfaceOpen" width="800px" append-to-body>
      <el-form ref="interfaceForm" :model="interfaceForm" label-width="150px">
        <el-form-item label="设备信息推送接口" prop="devicePushUrl">
          <el-input v-model="interfaceForm.devicePushUrl" placeholder="请输入设备信息推送接口" />
        </el-form-item>
        <el-form-item label="传感器数据推送接口" prop="dataPushUrl">
          <el-input v-model="interfaceForm.dataPushUrl" placeholder="请输入传感器数据推送接口" />
        </el-form-item>
        <el-form-item label="报警数据推送" prop="alarmPushUrl">
          <el-input v-model="interfaceForm.alarmPushUrl" placeholder="请输入传感器数据推送接口" />
        </el-form-item>
        <el-form-item label="APPID" prop="appId">
          <el-input v-model="interfaceForm.appId" placeholder="请输入APPID" readonly />
        </el-form-item>
        <el-form-item label="APP SECRET" prop="appSecret">
          <el-input v-model="interfaceForm.appSecret" placeholder="请输入appSecret"  readonly/>
        </el-form-item>
        <el-form-item label="白名单" prop="whiteList">
          <el-input type="textarea" v-model="interfaceForm.whiteList" placeholder="请输入白名单" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInterface">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompany, getCompany, delCompany, addCompany, updateCompany , getCompanyInterface, addCompanyInterface} from "@/api/ztIot/company";
import {options} from '@/api/system/country';
import { getToken } from '@/utils/auth'
export default {
  name: "Company",
  dicts: ['common_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileList:[],
      seriesList:[],
      uploadURL: process.env.VUE_APP_BASE_API + '/system/files?module=image',
      downloadUrl:process.env.VUE_APP_BASE_API + '/system/files/anonymous/download/',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      companyList: [],
      countryList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      interfaceOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        domain: null,
        contacts: null,
        contactsPhone: null,
      },
      // 表单参数
      form: {},
      interfaceForm:{},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        contacts: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        // abbreviation: [
        //   { required: false, message: "简称不能超过6个字符", max: 6 , trigger: "blur" }
        // ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.token = 'Bearer ' + getToken();
    this.getList();
    // this.getSeriesList();
    this.getCountryList()
  },
  methods: {
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCountryList(){
      options().then(res => this.countryList = res.data)
    },
    //查询网关
    // getSeriesList(){
    //   optionSeries().then(res => this.seriesList = res.data)
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.interfaceOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        seriesId:null,
        name: null,
        abbreviation:null,
        domain: null,
        contacts: null,
        contactsPhone: null,
        logo: null,
        masterId: null,
        intro: null,
        state: 1,
        username:'',
        password:''
      };

      this.interfaceForm = {
        id:null , 
        companyId:null,
        devicePushUrl:null,
        dataPushUrl:null,
        alarmPushUrl:null,
        appId:null,
        appSecret:null,
        whiteList:null
      }
      this.resetForm("form");
      this.resetForm("interfaceForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompany(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAddInterface(row){
      this.reset();
      this.interfaceForm.companyId = row.id;
      getCompanyInterface(row.id).then( res => {
        if(res.data) this.interfaceForm = res.data ;
      });
      this.interfaceOpen = true ;
    },
    submitInterface(){
      console.log(this.interfaceForm)
      addCompanyInterface(this.interfaceForm).then( res => {
          this.$modal.msgSuccess("修改成功");
          this.interfaceOpen = false;
          this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业信息编号为"' + ids + '"的数据项？').then(function() {
        return delCompany(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ztIot/company/export', {
        ...this.queryParams
      }, `company_${new Date().getTime()}.xlsx`)
    } ,

    handleRemove() {
      this.form.logo = '';
    },
    uploadSuccess(res) {
      this.$set(this.form, 'logo', res.data.id)
      this.$refs["form"].clearValidate('logo')
    },
    //跳转到设备管理
    toDeviceManager(row) {
      this.$router.push({
        path: '/sysDevice/device',
        query: { companyId: row.id }
      })
    },
    //跳转批控制
    toControlManager(row) {
      this.$router.push({
        path: '/sysDevice/deviceControl',
        query: { companyId: row.id }
      })
    },
  }
};
</script>

<style  lang="scss" scoped >

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>